package org.cybzacg.convert.strategy.impl;


import org.cybzacg.convert.context.ConversionContext;
import org.cybzacg.convert.core.TypeConverter;
import org.cybzacg.convert.enums.ConversionError;
import org.cybzacg.convert.enums.ConversionStrategyEnum;
import org.cybzacg.convert.exception.ConversionException;
import org.cybzacg.convert.strategy.ConversionStrategy;

/**
 * 严格转换策略
 * 在转换失败时抛出异常，不允许使用默认值
 *
 * @author cybzacg.blog
 * @version 3.0
 * @since 3.0
 */
public class StrictConversionStrategy implements ConversionStrategy {

    @Override
    public <T> T execute(
            TypeConverter converter,
            Object source, Class<T> targetType,
            T defaultValue,
            ConversionContext context
    ) throws ConversionException {

        if (source == null) {
            throw new ConversionException(ConversionError.NULL_VALUE,
                    "严格模式下不允许空值转换，目标类型: " + targetType.getSimpleName());
        }

        try {
            // 直接执行转换，不使用默认值
            T result = converter.convert(source, targetType, null, context);

            if (result == null) {
                throw new ConversionException(ConversionError.NULL_VALUE,
                        "严格模式下转换结果不能为null，目标类型: " + targetType.getSimpleName());
            }

            return result;

        } catch (Exception e) {
            if (e instanceof ConversionException) {
                throw e;
            }
            throw new ConversionException(ConversionError.CONVERSION_FAILED,
                    "严格模式下转换失败: " + e.getMessage(), e);
        }
    }

    @Override
    public ConversionStrategyEnum getName() {
        return ConversionStrategyEnum.STRICT;
    }

    @Override
    public String getDescription() {
        return "严格转换策略，转换失败时抛出异常，不允许使用默认值";
    }

    @Override
    public boolean supports(ConversionContext context) {
        return context != null && context.getStrategy().isStrict();
    }
}
